package com.augurit.gzcgwsp.smartformCsdlwj.web;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.JbpmException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.ExtUtils;
import com.augurit.common.util.lang.DateUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.csshlj.service.ICsshljCzService;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.smartformCsdlwj.common.SmartDao;
import com.augurit.gzcgwsp.smartformCsdlwj.entity.ShljysQtqk;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IShljqsQtqkService;
import com.augurit.gzcgwsp.smartformCsdlwj.service.ISmartFormShljqsService;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IYwHwXminfoService;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IYwShljqsService;
import com.augurit.gzcgwsp.smartformCsdlwj.web.form.ShljqsForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjcllistService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjtzsScclService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjtzsScclForm;
import com.augurit.smartform.factory.ScriptEngineFactory;
import com.augurit.smartform.service.IFormExecuteService;
import com.augurit.smartform.service.IWfSupportService;
import com.augurit.smartform.test.TestService;
import com.augurit.wf.app.doccode.service.IOaDocCodeService;
import com.augurit.wf.bi.service.IWfBusInstanceService;
import com.augurit.wf.bi.web.form.WfActElemPrivDefForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.form.TraceRecord;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.tag.opinion.WfOpinionTag;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientExtAction;

/**
 * 从事陆域城市生活垃圾经营性清扫、收集、运输服务许可审批
 * @author Administrator
 *
 */
@SuppressWarnings( { "serial", "unchecked" })
@Results( {
		@Result(name ="preViewSjtzs", location ="/gzcgwsp/shljqs/preViewSjtzs.jsp"),
		@Result(name ="printViewZs", location ="/gzcgwsp/shljqs/preViewXkz.jsp"),
		@Result(name ="printViewfb", location ="/gzcgwsp/shljqs/preViewfb.jsp"),
		@Result(name ="printViewfb2", location ="/gzcgwsp/shljqs/preViewfb2.jsp"),
		@Result(name = CrudActionSupport.RELOAD, location = "smart-form-shljqs.action", type = "redirect"),
		@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
		@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
		@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/shljqs/ShljqsBa-input.jsp"),
		@Result(name = "printxkzs", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
		
		@Result(name = "printsjtzs", location = "/gzcgwsp/wfex/client/wf-printsjtzs.jsp"),
		@Result(name = "printfb", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
		@Result(name = "opinions", location = "/gzcgwsp/shljys/shljysOpinions.jsp"),
		@Result(name = "toBjgzData", location = "/gzcgwsp/shljqs/shljqs-bjgz.jsp"),
	    @Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/qumake-noline-document.jsp"),
		@Result(name = "shlj-qtqk", location = "/gzcgwsp/shljys/shljys-qtqk.jsp") })
public class SmartFormShljqsAction extends WfBusClientExtAction {
	private static final Logger log=Logger.getLogger(SmartFormShljqsAction.class);
	@Autowired
	private TestService testService;

	@Autowired
	private IWfSupportService wfSupportService;

	@Autowired
	private IFormExecuteService formExecuteService;
	@Autowired
    private IWfServiceEX wfServiceEX;

	@Autowired
	private IOaDocCodeService docCodeService;

	@Autowired
	private IOaDocCodeServiceEX oaDocCodeServiceEX;

	@Autowired
	private IWfBusInstanceService wfBusInstanceService;

	@Autowired
	private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;

	@Autowired
	private SmartDao smartDao;

	@Autowired
	private IShljqsQtqkService shljqsQtqkService;
	

	@Autowired
	private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
	@Autowired
	private ISmartFormShljqsService smartFormShljqsService;

	@Autowired
	private IYwShljqsService ywShljqsService;

	@Autowired
	private ICsshljCzService csshljCzService;
	
	@Autowired
	private IWfService wfService;
	
	@Autowired
	private IYwPrintDocService ywPrintDocService;
	
	@Autowired
	private IYwHwXminfoService ywHwXminfoService;
	@Autowired
	private IYwComSjcllistService ywComSjcllistService;
	@Autowired
	private IYwComSjtzsScclService ywComSjtzsScclService;

	private Page<ShljqsForm> page = new Page<ShljqsForm>(20);
	private Map pageMap = new HashMap();

	private Long id;
	private ShljqsForm form;
	private ShljysQtqk shljysQtqk;

	/**
	 * 
	 * @return
	 * @throws IOException
	 */
	public String wfBusSave() throws IOException {
		this.executeWfSaveServer(); // 保存之前执行后端JS函数		
		try {	
			Map map = getMapByRequest(getRequest());
			//String username=this.getLoginUser().getUser().getUserName();
			OmUserForm userForm=getLoginUser().getUser();
			WfBusInstanceTaskForm task=smartFormShljqsService.wfBusSave(getRequest(),form,map, userForm);
			if(task==null){
				Struts2Utils.renderJson("{\"success\":false,\"errorMsg\":\"" + "保存失败请确认是否有此权限" + "\"}");
				return null;
			}
			
			WfUtils.renderWfBusSaveJson(task, form);
		} catch (Exception e) {
			WfBusSaveResult result = new WfBusSaveResult(true, "保存失败");
			Struts2Utils.renderJson(result);
			log.error("保存出现错误"+e);
		}
		
		return null;
	}
	
	/**
	 * 预览收件通知书
	 * @return 
	 * @throws Exception
	 */
	public String preViewSjtzs() throws Exception {
		String activName = getRequest().getParameter("activName");
		getRequest().setAttribute("activName",activName);
		YwComSjcllistForm ywComSjcllistForm = new YwComSjcllistForm();
		ywComSjcllistForm.setTplcode(form.getTemplateCode());
		List<YwComSjcllistForm> sjclList = ywComSjcllistService.getList(ywComSjcllistForm);
		System.out.println("sjclList.size() = " + sjclList.size());
		this.getRequest().setAttribute("sjclList", sjclList);
		//查询是否有已经选择的,有的话，默认选中
		YwComSjtzsScclForm ywComSjtzsScclForm = new YwComSjtzsScclForm();
		ywComSjtzsScclForm.setAcceptNo(form.getAcceptNo());
		ywComSjtzsScclForm.setAjid(form.getId());
		ywComSjtzsScclForm.setTplcode(form.getTemplateCode());
		List<YwComSjtzsScclForm> checkedsjclList = ywComSjtzsScclService.getList(ywComSjtzsScclForm);
		System.out.println("checkedsjclList.size() = "+checkedsjclList.size());
		String checkedsStr = "";
		if(checkedsjclList != null && checkedsjclList.size() > 0){
			for(int i = 0;i<checkedsjclList.size();i++){
				checkedsStr = checkedsStr + "===" + checkedsjclList.get(i).getClid();
			}
		}
		getRequest().setAttribute("checkedsStr", checkedsStr);
        return "preViewSjtzs";
    }
	
	/**
	 * 保存收件通知书材料
	 * @return
	 * @throws Exception
	 */
	public String saveSjtzs() throws Exception {
		String path = "";
		try {
			String [] checkedIds = getRequest().getParameterValues("checkedIds");//选中的checkbox
			String context=getRequest().getSession().getServletContext().getRealPath("");
			path = smartFormShljqsService.saveSjtzs(checkedIds, context, form,
					getLoginUser());
			System.out.println("path = "+path);
			getRequest().setAttribute("path", path);
			getResponse().getWriter().print("success"+"&&"+path);
		} catch (Exception e) {
			e.printStackTrace();
			getResponse().getWriter().print("false");
		}
		
        return null;
    }
	
	/**
	 * 打印收件通知书
	 * @return
	 */
	public String printSjtzs(){
//		String checkedsStr = getRequest().getParameter("checkedsStr");//选中的checkbox
//		System.out.println("checkedsStr = "+checkedsStr);
//		YwComSjcllistForm ywComSjcllistForm = new YwComSjcllistForm();
//		ywComSjcllistForm.setTplcode(form.getTemplateCode());
//		String context=getRequest().getSession().getServletContext().getRealPath("");
//		String path = smartFormShljqsService.printSjtzs(context, ywComSjcllistForm,form,checkedsStr,this.getLoginUser().getUser().getUserName());
//		System.out.println("path = "+path);
		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), "sjtzs", form.getId());
		form.setFileCode("sjtzs");
    	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
			return WfConstant.PRINT_DIR;
		}
		return WfConstant.PRINT_DIR;
	}
	
	/**
	 * 到补交告知页面
	 * @return
	 */
	public String toBjgz(){
		LoginUserForm form=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=form.getUser().getUserName();
		this.getRequest().setAttribute("CurrUserName", username);
		setOpinions();
		return "toBjgzData";
	}
	
	/**
	 * 插入延期天数补交告知的信息
	 * @return
	 */
	public String insertOtherInfo(){
		Map map=this.getMapByRequest(this.getRequest());
		this.smartFormShljqsService.saveOherInfo(map);
		
	  return null;
	}
	
	public String wfBusYslTuih() throws Exception {
    	try {
    		smartFormShljqsService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }

	/**
	 * 新增或修改
	 */
	@Override
	public String input() throws Exception {

		return INPUT;
	}
	
	/**
	 * 获取意见页面
	 * @return
	 */
	public String getOpinions(){
		String CurrUserName=this.getLoginUser().getUser().getUserName();
		String area=smartFormShljqsService.getArea(form);
		getRequest().setAttribute("CurrUserName", CurrUserName);
		getRequest().setAttribute("area", area);
		getRequest().setAttribute("fzsjstr", form.getFzsjstr());
		getRequest().setAttribute("validstarttime", form.getValidstarttime());
		getRequest().setAttribute("validendtime", form.getValidendtime());
		this.setOpinions();
		return "opinions";
	}
	
	
    /**
     * ntko控件套打许可证书
     * @return
     */
    public String printXkz() throws Exception{
        try {
            String tempPath="Templates/printTemplate/csshlj/czxkz.xls";
            logger.info("打印经营许可证的文件路径"+tempPath);
           String context=getRequest().getSession().getServletContext().getRealPath("");
           String inpath=context+File.separator+tempPath;
           tempPath=smartFormShljqsService.writeXkzData(form,context,inpath);
           getRequest().setAttribute("templateFilePath",tempPath);
           logger.info("返回设施一览表文件路径"+tempPath);
       } catch (Exception e) {
           log.error("转换模版文件出现错误");
       }
       return "printxkzs";
    }
	/**
	 * 套打副本
	 * @return
	 * @throws Exception
	 */
	public String printFb() throws Exception{
		 try {
	            String tempPath="Templates/printTemplate/csshlj/fbzs.xls";
	            logger.info("打印经营许可证的文件路径"+tempPath);
	           String context=getRequest().getSession().getServletContext().getRealPath("");
	           String inpath=context+File.separator+tempPath;
	           tempPath=this.smartFormShljqsService.writeFbData(form,context,inpath);
	           getRequest().setAttribute("templateFilePath",tempPath);
	           logger.info("返回设施一览表文件路径"+tempPath);
	       } catch (Exception e) {
	           log.error("转换模版文件出现错误");
	       }
		  return "printfb";
	  }
	
	/**
	 * 打印查看许可证书
	 * @return
	 */
	public String preViewXkz(){
	  	String taskId=getRequest().getParameter("taskId");
	  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
		String activName=instance.getActivityName();
		if("jbrsj".equals(activName)){
			form.setFzjg(getLoginUser().getOrg().getOrgName());
		}
	    getRequest().setAttribute("hjmc", activName);
	    return "printViewZs";
	}
	
	/**
	 * 打印查看副本
	 * @return
	 */
	public String printViewFb(){
		String taskId=getRequest().getParameter("taskId");
	  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
		String activName=instance.getActivityName();
	    getRequest().setAttribute("hjmc", activName);
	  return "printViewfb";
	}
	
	/**
	 * 查看副本第二页
	 * @return
	 */
	public String printViewFb2(){
	    getRequest().setAttribute("hjmc", getRequest().getParameter("hjmc"));
	  return "printViewfb2";
	}
	
	/**
	 * 保存许可证
	 * @return
	 * @throws IOException 
	 */
	public String saveXkz() throws IOException{
		   try {
			   reSetForm(form);
			this.smartFormShljqsService.doUpdate(form,"HW_SHLJQS_V1");
		} catch (Exception e) {
			
		}
		getResponse().getWriter().print("success");
			return null;
	}

	public String getDZbCZSummary() throws Exception {
		//Map map = getRequest().getParameterMap();
		//String cbyw = BaseAction.getRequest().getParameter("cbyw");
		//System.out.println("sldate:="+form.getSlrqbegin());
		//String qyname=String.valueOf(map.get("qyname"));		
		ExtUtils.initPageFromExtGridParam(getRequest(), page);
		Map map=getMapByRequest(getRequest());
		smartFormShljqsService.getDbData(page,map);
		//wfTaskSummaryServiceEX.getDbAndZbSummary(page, form, this.getLoginUserName(), this.getGroupBy(), this.getGroupDir());
		renderText(Struts2Utils.getJsonString(page, DateUtils.YYYY_MM_DD_HH_MM_SS));
		return null;
	}
	
	/**
	 * 保存副本
	 * @return
	 * @throws Exception
	 */
	public String saveFb() throws Exception{
		   try {
			    reSetForm(form);
				this.smartFormShljqsService.doUpdateFb(form,"HW_SHLJQS_V1");
				
				Map map=getMapByRequest(getRequest());
				ywHwXminfoService.saveByMap(map,null);
				
			} catch (Exception e) {
				
			}
			getResponse().getWriter().print("success");
				return null;
	}
	
	/**
	 * 保存副本第二页的项目日期信息
	 * @return
	 * @throws Exception
	 */
	public String saveFb2() throws Exception{
		   try {
				Map map=getMapByRequest(getRequest());
				smartFormShljqsService.doUpdateFb(form,"HW_SHLJQS_V1");
				ywHwXminfoService.saveByMap(map,null);
				
			} catch (Exception e) {
				
			}
			getResponse().getWriter().print("success");
			return null;
	}
	
    /**
     * 设置form数据
     * @param form
     */
	private void reSetForm(ShljqsForm form){		
		this.smartFormShljqsService.reSetForm(form);
	}
	
	public String printcz() throws Exception {
		String taskId=getRequest().getParameter("taskInstDbid");
		String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		}else{
			activName=getRequest().getParameter("activName");
		}
		getRequest().setAttribute("activName", activName);
		form.setCbyw("广州市（陆域）城市生活垃圾经营性清扫、收集、运输服务");
		form.setCbyw2("广州市（陆域）城市生活垃圾经营性清扫、收集、运输服务");
		form.setCbyw3("广州市（陆域）城市生活垃圾经营性清扫、收集、运输服务");
		form.setCbyw4("广州市（陆域）城市生活垃圾经营性清扫、收集、运输服务");
		if(form.getId() != null && form.getId() > 0){
			String templateCode = form.getTemplateCode();
			String fileCode = form.getFileCode();
			form =smartFormShljqsService.getForm(form.getId(), "hw_shljqs_v1");
			//加载收件通知书里面的附件
			form = smartFormShljqsService.getSjtzsField(form);
    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(templateCode, fileCode, form.getId());
    		if("hwcCpb".equals(fileCode)){
    			form = printHwcCpb();
    		}
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
        		YwPrintDocForm doc=ywPrintDocFormList.get(0);
        		if("sjtzs".equals(doc.getFileCode())){
        			String path=doc.getPath();
        			getRequest().setAttribute("templateFilepath", path);
        			return "printsjtzs";
        		}else{
        			return WfConstant.PRINT_DIR;
        		}
    			
    		}
    	}
		
        return WfUtilsEX.wfBusPrint(form,form.getId(),activName);
    }
	
	public ShljqsForm printHwcCpb(){
		String viewName=getRequest().getParameter("viewName");
		if(viewName == null){
			throw new JbpmException("视图参数不能为空，无法正确加载历史意见列表！");
		}
		
		Map<String, List<TraceRecord>> map = null;
		if(viewName.equals(WfActElemPrivDefForm.DB_ZB_VIEW)){
			map = loadWfOpinionsByTaskInstDbid();
		}
		else{
			map = loadWfOpinionsByProcInstDbid();
		}
		if(map != null){
               Iterator it=map.entrySet().iterator();
               while(it.hasNext()){
            	   	Map.Entry entrys=(Map.Entry)it.next();
            	   	String key=(String) entrys.getKey();
            	   	List<TraceRecord> traceRecords = (List<TraceRecord>) entrys.getValue();
            	   	StringBuilder opinionsStr = new StringBuilder("");
           			if(traceRecords != null && traceRecords.size() > 0){
//           				jbryskc  kzyj  jfgld  jldyj
           				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
           				String handleComments = traceRecords.get(traceRecords.size()-1).getHandleComments();
           				String assignee = traceRecords.get(traceRecords.size()-1).getAssignee();
           				String handleCommentsTimeStr = "";
           				Date handleCommentsTime = traceRecords.get(traceRecords.size()-1).getHandleCommentsTime();
           				if(handleCommentsTime != null){
           					handleCommentsTimeStr = sf.format(handleCommentsTime);
           				}
           				if("jbryskc".equals(key)){
           					form.setJbryskcYj(handleComments);
           					form.setJbryskcRy(assignee);
           					form.setJbryskcSj(handleCommentsTimeStr);
           				}
						if("kzyj".equals(key)){
							form.setKzyjYj(handleComments);
							form.setKzyjRy(assignee);
							form.setKzyjSj(handleCommentsTimeStr);
						}
						if("jfgld".equals(key)){
							form.setJfgldYj(handleComments);
							form.setJfgldRy(assignee);
							form.setJfgldSj(handleCommentsTimeStr);
						}
						if("jldyj".equals(key)){
							form.setJldyjYj(handleComments);
							form.setJldyjRy(assignee);
							form.setJldyjSj(handleCommentsTimeStr);
						}
           			}
               }
		}
		return form;
	}

	/**
	 * 检查是否存在收件通知书
	 * @return
	 * @throws IOException 
	 */
	public String checkSjtzs() throws IOException{
		String templateCode = form.getTemplateCode();
		String fileCode = form.getFileCode();
		form =smartFormShljqsService.getForm(form.getId(), "hw_shljqs_v1");
		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(templateCode, fileCode, form.getId());
		if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
			getResponse().getWriter().print("exsit");
		}
		return null;
	}
	
	/**
	 * 制文
	 * 
	 * @return
	 * @throws Exception
	 */
	public String makeDocument() throws Exception {
		setOpinions();
		//加载收件通知书里面的附件
		form = smartFormShljqsService.getSjtzsField(form);
		if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
			String redHeadFilePath = wfBusTemplateServiceEX
					.getPrintTemplatePath(Long.parseLong(form
							.getRedHeadFileId()));
			form.setRedHeadFilePath(redHeadFilePath);
		}
		
		//加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果要打印红头
		 if("yes".equals(isred)){
			 String redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      form.setRedHeadFilePath(redHeadFilePath);
		 }
		String templateCode = getTemplateCode();
		if (templateCode != null && templateCode.trim().length() > 0) {
			form.setQu(getLoginUser().getOrg().getOrgName().substring(0,2));
			String printTemplatePath = wfBusTemplateServiceEX
					.getPrintTemplatePath(
							templateCode,
							WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
			form.setTemplatePath(printTemplatePath);
			form.setCbyw("(陆域)城市生活垃圾经营性清扫、收集、运输服务许可审批");
			
	//		form.setFzjg("广州市城市管理委员会");
	//		form.setTzlxr(getLoginUser().getUser().getUserName());
			WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = (WfTemplateAttachmentRefFormEX) wfTemplateAttachmentRefServiceEX
					.get(Long.parseLong(form.getZhengwenFileId()));
			String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath()
					+ "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
			form.setZhengwenPath(zhengwenPath);
			String slrq=smartFormShljqsService.getSlrq(form.getId(),wfTemplateAttachmentRefFormEX.getFileCode(),wfTemplateAttachmentRefFormEX.getId());
			if(StringUtils.isBlank(slrq))
				form.setSlrq(DateUtilsEX.convertDate2Chinese(new Date()));
			else
				form.setSlrq(slrq);
			form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
			form.setCurYear(String.valueOf(Calendar.getInstance().get(
					Calendar.YEAR)));
			   Long seq=oaDocCodeServiceEX.getQuCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),
	            		form.getId(),this.getLoginUser());
	             if(seq.intValue()<10){
		        	  form.setCurSeq("0"+String.valueOf(seq));
		        }else{
		        	  form.setCurSeq(String.valueOf(seq));
		        }
//			form.setCurSeq(String.valueOf(oaDocCodeServiceEX
//					.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId())));
			BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
			List list = smartFormShljqsService.getListById(form.getId());
			WfUtilsEX.wfBusSmartFormPrint(form, list);
			BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
			BaseAction.getRequest().setAttribute("fileCode",
					wfTemplateAttachmentRefFormEX.getFileCode());
			BaseAction.getRequest().setAttribute("entityId", form.getId());
			BaseAction.getRequest().setAttribute("templateId",
					wfTemplateAttachmentRefFormEX.getId());
		}
		return WfConstant.MAKE_DOCUMENT;
	}
	
	
	/**
	 * 页面保存之前执行业务逻辑
	 */
	private void executeWfSaveServer() {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpServletRequest request = this.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine = ScriptEngineFactory
				.getBindingScriptEngine(map);
		formExecuteService.executeWfSaveServer(scriptEngine, request);
	}

	private void setEngineMap(Map map) {
		map.put("request", this.getRequest());
		map.put("response", this.getResponse());
		map.put("service", formExecuteService);
		map.put("page", page);
		map.put("pageMap", pageMap);
		map.put("testService", testService);
	}
	
	/**
	 * 加载历史意见到制文中
	 */
	private void setOpinions(){
		String viewName=getRequest().getParameter("viewName");
		if(viewName == null){
			throw new JbpmException("视图参数不能为空，无法正确加载历史意见列表！");
		}
		
		Map<String, List<TraceRecord>> map = null;
		if(viewName.equals(WfActElemPrivDefForm.DB_ZB_VIEW)){
			map = loadWfOpinionsByTaskInstDbid();
		}
		else{
			map = loadWfOpinionsByProcInstDbid();
		}		StringBuilder opinionsStr = new StringBuilder("");
		if(map != null){
               Iterator it=map.entrySet().iterator();
               while(it.hasNext()){
            	   Map.Entry entrys=(Map.Entry)it.next();
            	   String key=(String) entrys.getKey();
            	   List<TraceRecord> traceRecords = (List<TraceRecord>) entrys.getValue();
            	   this.setOpinion(key, traceRecords);
             }
		}
		
		getRequest().setAttribute(WfOpinionTag.WF_OPINIONS, map);
	}
	
	/**
	 * 环节名称判断是哪个环节的意见
	 */
	private void setOpinion(String hjmc, List<TraceRecord> traceRecords){
		StringBuilder opinionsStr = new StringBuilder("");
		if(traceRecords != null && traceRecords.size() > 0){
				for(TraceRecord traceRecord:traceRecords){
					if(traceRecord.getHandleComments() != null && traceRecord.getHandleComments().trim().length() > 0){
						opinionsStr.append(traceRecord.getHandleComments());
					}
				}
		}
/*		if("jbrcs".equals(hjmc)){//
			form.setCsyj(opinionsStr.toString());
		}else if("czgldsh".equals(hjmc) || "cfgldsh".equals(hjmc)){
			String content=form.getFsyj()==null?"":form.getFsyj();
			if(StringUtils.isNotBlank(opinionsStr.toString())){
				content+=opinionsStr.toString()+"\n";
			}
			form.setFsyj(content);
		}else if("wfgldsh".equals(hjmc)){
			form.setSpyj(opinionsStr.toString());
		}*/
		
	}
	
	public String getYsQtqk(){
        String ywid=getRequest().getParameter("ajid");
        System.out.println(ywid);
		if(ywid !=null){
			shljysQtqk = shljqsQtqkService.get(Long.parseLong(ywid));
			System.out.println(shljysQtqk.getId());
			System.out.println("------------");
			System.out.println(shljysQtqk.getYscdmj());
			System.out.println("------------");
			if(shljysQtqk==null){
				shljysQtqk =new ShljysQtqk();
				shljysQtqk.setYwid(Long.parseLong(ywid));
			}else{
				System.out.println("not null;");
			}
	//		getRequest().setAttribute("shljysQtqk", shljysQtqk);
		}
		return "shlj-qtqk";
	}

	public String doUpdate() throws Exception{ 
        Map<String, String> map = new HashMap<String, String>();
        Enumeration enu = getRequest().getParameterNames();
        while(enu.hasMoreElements()) {   
            String paraName = (String)enu.nextElement();   
            String paraValue = getRequest().getParameter(paraName).trim(); 
            if(paraValue!=null && !"".equals(paraValue)){
                map.put(paraName, paraValue);
            }           
        }
        JSONObject jsonObject = JSONObject.fromObject(map); 
        ShljysQtqk entity=(ShljysQtqk) JSONObject.toBean(jsonObject, ShljysQtqk.class);
        try {
        	shljqsQtqkService.save(entity);
			getResponse().getWriter().print("success");
		} catch (Exception e) {
			getResponse().getWriter().print("fail");
		}
		
         return null;
   }
	
	public void doUpdateFym(){

		String id=getRequest().getParameter("fid");
		String fzsj=getRequest().getParameter("fzsj");
		String xmqy=getRequest().getParameter("xmqy");
		String fzh=getRequest().getParameter("fzh");
		String jysjs=getRequest().getParameter("jysjs");
		String jysje=getRequest().getParameter("jysje");
		String sql = "Update HW_SHLJQS_V1 SET FZH ='"
			+ fzh + "' , XMQY = '"
			+ xmqy+ "' , FZSJSTR = '"
			+ fzsj+ "' , JYSJESTR = '"
			+ jysje+ "' , JYSJSSTR = '"
			+ jysjs
			+ "' where ID = " + Long.parseLong(id);
		//System.out.println("sql:="+sql);
		//smartDao.executeSql(sql);

	}
	

	
	/**
	 * 窗口导入前检查
	 * @return
	 * @throws Exception
	 */	
	public String checkImportData() throws Exception{
        String id=getRequest().getParameter("id");
        String templateCode=getRequest().getParameter("templateCode");
        //先查询收件材料是否存在
        boolean flag=this.smartFormShljqsService.checkData(templateCode,"申请表",Long.valueOf(id),null);
        if(flag){
        }else{
            getResponse().getWriter().print("dataNotExist");
        }
	    
	    return null;
	}
	
	   /**
     * 窗口收案环节导入数据
     */
    public String  importData() throws Exception{
        Map map=getMapByRequest(getRequest());
        String contextPath=getRequest().getSession().getServletContext().getRealPath("");
        map.put("contextPath", contextPath);
        map.put("filename", "申请表");
        String result=this.smartFormShljqsService.importData(form,map);
        if(result==null)
        	   getResponse().getWriter().print("");
        else
        getResponse().getWriter().print(result);
        
        return null;
    }
	
    /**
     *获取返回后导入的数据
     * @return
     * @throws IOException 
     */
    public String getResultImportData () throws IOException{
    	String id=getRequest().getParameter("id");
       if(StringUtils.isNotBlank(id)){
    	   List list=this.ywShljqsService.getListById(Long.valueOf(id));
    	   Map map=(Map) list.get(0);
           JSONObject jsonObject = JSONObject.fromObject(map); 
           getResponse().getWriter().print(jsonObject.toString());
       }
        return null;
    }
        
	 private  Map getMapByRequest(HttpServletRequest request) {
	        Map<String, String> map = new HashMap<String, String>();
	        Enumeration enu = request.getParameterNames();
	        while(enu.hasMoreElements()) {   
	            String paraName = (String)enu.nextElement();   
	            String paraValue = request.getParameter(paraName).trim(); 
	           // if(paraValue!=null && !"".equals(paraValue)){
	                map.put(paraName, paraValue);
	            //}           
	        }
	                
	        return map;
	} 


		/**
		 * 生成证书编号
		 * @return
		 */
	public String createZsbh() throws IOException{
			
		Map map=this.getMapByRequest(getRequest());	
		String taskId=(String) map.get("taskId");
		String actname=(String) map.get("actname");//经办人办结
		if(StringUtils.isNotBlank(taskId)){
			WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			String activName=instance.getActivityName();
			if(actname.equals(activName)){
				String zsbh=csshljCzService.createZsbh(map,id);
				getResponse().getWriter().print(zsbh);
			}
		}
		return null;
	}
	
	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {			
			if(id!=null){
				form =smartFormShljqsService.getForm(id, "hw_shljqs_v1");
				Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
	    		if(date!=null){
	    			form.setDfsj(date);
	    		}
			
			}else{
				form = new ShljqsForm();
			}
			//补交告知原因
	    	if(form.getBjgzyy()==null){
	    		form.setBjgzyy(this.getOpinion("jbrsl"));
	    	}
	    	//补交告知时间
	    	if(form.getBjgzsj()==null){
	    		form.setBjgzsj(new Date());
	    	}
	}
	
	

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public ShljqsForm getModel() {
		// TODO Auto-generated method stub
		return form;
	}

	public Page<ShljqsForm> getPage() {
		return page;
	}

	public void setPage(Page<ShljqsForm> page) {
		this.page = page;
	}

	public ShljysQtqk getShljysQtqk() {
		return shljysQtqk;
	}

	public void setShljysQtqk(ShljysQtqk shljysQtqk) {
		this.shljysQtqk = shljysQtqk;
	}
}
